<template>
  <div class="map-container">
    <div class="map" id="map-container" ref="mapContainer"></div>
    <div class="map-controls">
      <el-input 
        v-model="searchAddress" 
        placeholder="搜索地址" 
        class="address-input"
        @keyup.enter="searchLocation"
      >
        <template #append>
          <el-button @click="searchLocation">
            <el-icon><Search /></el-icon>
          </el-button>
        </template>
      </el-input>
      <p class="current-location">当前位置: {{ currentLocation }}</p>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, defineComponent } from 'vue'
import { Location, Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

export default defineComponent({
  name: 'MapSelector',
  components: {
    Location,
    Search
  },
  props: {
    initialLocation: {
      type: String,
      default: '北京市'
    }
  },
  emits: ['locationConfirmed'],
  setup(props, { emit }) {
    const mapContainer = ref(null)
    const searchAddress = ref('')
    const currentLocation = ref(props.initialLocation || '北京市')
    let map = null
    let marker = null
    let geoc = null // 地理编码解析器
    let localSearch = null // 本地搜索
    
    // 初始化地图
    const initMap = () => {
      if (!window.BMapGL) {
        console.warn('百度地图 API 尚未加载，等待加载...')
        setTimeout(initMap, 300) // 等待加载
        return
      }
      
      try {
        // 创建地图实例
        map = new window.BMapGL.Map("map-container")
        
        // 初始化中心点（北京市中心）
        const initialPoint = new window.BMapGL.Point(116.404, 39.915)
        map.centerAndZoom(initialPoint, 12)
        
        // 开启鼠标滚轮缩放
        map.enableScrollWheelZoom(true)
        
        // 创建地址解析器实例
        geoc = new window.BMapGL.Geocoder()
        
        // 创建本地搜索实例
        localSearch = new window.BMapGL.LocalSearch(map, {
          renderOptions: { map: map },
          onSearchComplete: function(results) {
            if (localSearch.getStatus() === window.BMAP_STATUS_SUCCESS) {
              // 获取第一个结果
              if (results.getCurrentNumPois() > 0) {
                const poi = results.getPoi(0)
                setMapCenter(poi.point)
                updateMarker(poi.point)
                
                // 更新位置名称
                geoc.getLocation(poi.point, function(rs) {
                  if (rs && rs.addressComponents) {
                    const address = rs.addressComponents
                    currentLocation.value = `${address.province} ${address.city} ${address.district} ${address.street} ${address.streetNumber}`
                  } else {
                    currentLocation.value = searchAddress.value
                  }
                })
              }
            } else {
              ElMessage.warning('未找到位置')
            }
          }
        })
        
        // 初始位置解析
        if (props.initialLocation) {
          searchAddress.value = props.initialLocation
          searchLocation()
        }
        
        // 添加点击事件
        map.addEventListener('click', function(e) {
          // 百度地图GL版中，点击事件返回的是e.latlng
          const point = e.latlng || e.point
          updateMarker(point)
          
          // 获取地址信息
          geoc.getLocation(point, function(rs) {
            if (rs && rs.addressComponents) {
              const address = rs.addressComponents
              currentLocation.value = `${address.province} ${address.city} ${address.district} ${address.street} ${address.streetNumber}`
            }
          })
        })
        
        // 添加缩放控件
        const zoomCtrl = new window.BMapGL.ZoomControl()
        map.addControl(zoomCtrl)
        
        // 添加比例尺控件
        const scaleCtrl = new window.BMapGL.ScaleControl()
        map.addControl(scaleCtrl)
        
        console.log('百度地图初始化成功')
      } catch (error) {
        console.error('百度地图初始化失败:', error)
        ElMessage.error('地图初始化失败')
      }
    }
    
    // 设置地图中心点
    const setMapCenter = (point) => {
      if (map && point) {
        map.centerAndZoom(point, 15)
      }
    }
    
    // 更新标记位置
    const updateMarker = (point) => {
      if (map && point) {
        if (marker) {
          map.removeOverlay(marker)
        }
        marker = new window.BMapGL.Marker(point)
        map.addOverlay(marker)
      }
    }
    
    // 搜索位置
    const searchLocation = () => {
      if (!searchAddress.value) {
        ElMessage.warning('请输入地址')
        return
      }
      
      if (map && localSearch) {
        try {
          localSearch.search(searchAddress.value)
        } catch (error) {
          console.error('搜索位置失败:', error)
          ElMessage.error('搜索位置失败')
        }
      } else {
        ElMessage.warning('地图尚未初始化')
      }
    }
    
    // 确认选择的位置
    const confirmLocation = () => {
      ElMessage.success(`确认选择位置: ${currentLocation.value}`)
      emit('locationConfirmed', currentLocation.value)
    }
    
    onMounted(() => {
      // 延迟加载，确保DOM已经渲染并等待百度地图API加载
      setTimeout(() => {
        initMap()
      }, 500)
    })
    
    onUnmounted(() => {
      // 清理地图实例
      if (map) {
        map = null
      }
    })
    
    return {
      mapContainer,
      searchAddress,
      currentLocation,
      searchLocation,
      confirmLocation
    }
  }
})
</script>

<style scoped>
.map-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 450px;
}

.map {
  width: 100%;
  height: 350px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.map-controls {
  margin-top: 10px;
}

.address-input {
  margin-bottom: 10px;
}

.current-location {
  font-size: 14px;
  color: #606266;
  margin: 5px 0;
}
</style> 